package com.youlai.eng.service;

import cn.hutool.core.lang.Assert;
import com.youlai.eng.entity.EngItemEntity;
import com.youlai.eng.query.PageQuery;
import com.youlai.eng.repository.EngItemRepository;
import com.youlai.utils.DateUtils;
import com.youlai.system.util.SecurityUtils;
import com.youlai.core.security.model.SysUserDetails;
import com.youlai.system.service.SysDictService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EngItemService {
    @Autowired
    private EngItemRepository repository;

    @Resource
    SysDictService sysDictService;

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public Page<EngItemEntity> getPage(PageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        DateUtils.toDatabaseFormat(queryParams, "startUpdateTime", "endUpdateTime");

        Sort sort =  Sort.by(Sort.Direction.DESC,"updateTime");   // .and(Sort.by("createTime").descending());
        Pageable pageable = PageRequest.of(pageNum-1, pageSize, sort);
        //动态查询
        Specification<EngItemEntity> spec  = (Root<EngItemEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StringUtils.isNotBlank(queryParams.getName())) {
                predicates.add(criteriaBuilder.like(root.get("name"), "%" + queryParams.getName() + "%"));
            }
            if (queryParams.getCode() != null) {
                predicates.add(criteriaBuilder.equal(root.get("code"), queryParams.getCode()));
            }

            if (queryParams.getStartUpdateTime() != null && queryParams.getEndUpdateTime() != null) {
                Date StartUpdateTimeDate = DateUtils.strToDateLong(queryParams.getStartUpdateTime());
                Date endUpdateTimeDate = DateUtils.strToDateLong(queryParams.getEndUpdateTime());
                predicates.add(criteriaBuilder.between(root.get("updateTime"), StartUpdateTimeDate, endUpdateTimeDate));
            }
            //查询发送成功并且未删除的
            predicates.add(criteriaBuilder.equal(root.get("deleted"), 0));
            Predicate predicate = criteriaBuilder.and(predicates.toArray(new  Predicate[predicates.size()]));

            if (StringUtils.isNotBlank(queryParams.getKeywords())) {
                Predicate predicateOr =  criteriaBuilder.or(
                    criteriaBuilder.like(root.get("itemName"), queryParams.getKeywords()),
                    criteriaBuilder.like(root.get("itemNo"), queryParams.getKeywords())
                );
                predicate = criteriaBuilder.and(predicate, predicateOr);
            }
            return predicate;
        };
        Page<EngItemEntity> page = repository.findAll(spec, pageable);
        return page;
    }

    public void save(EngItemEntity entity){
        // 校验员工编号是否存在
        String itemNo = entity.getItemNo();
        Specification<EngItemEntity> spec  = (Root<EngItemEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
            Predicate predicate = cb.and(cb.equal(root.get("itemNo"), itemNo));
            return predicate;
        };
        long count = repository.count(spec);
        Assert.isTrue(count == 0, "该货号已存在");

        SysUserDetails user = SecurityUtils.getUser();
        entity.setCreateBy(user.getUserId());
        entity.setCreateName(user.getUsername());
        entity.setUpdateBy(user.getUserId());
        entity.setUpdateName(user.getUsername());
        repository.save(entity);
    }

    public void update(EngItemEntity entity){
        // 校验员工编号是否存在
        String itemNo = entity.getItemNo();
        Specification<EngItemEntity> spec  = (Root<EngItemEntity> root, CriteriaQuery<?> cq, CriteriaBuilder cb) -> {
            Predicate predicate = cb.and(cb.equal(root.get("itemNo"), itemNo));
            predicate = cb.and(cb.notEqual(root.get("id"), entity.getId()),predicate);
            return predicate;
        };
        long count = repository.count(spec);
        Assert.isTrue(count == 0, "该货号已存在");

        SysUserDetails user = SecurityUtils.getUser();
        entity.setUpdateBy(user.getUserId());
        entity.setUpdateName(user.getUsername());

        //处理优选库的问题
        String storebin = entity.getStorebin();
        if(storebin!=null && !"".equals(storebin)) {
            String[] storebins = storebin.split(",");
            entity.setStore(storebins[0]);
            entity.setBin(storebins[1]);
        }
        repository.save(entity);
    }

    public EngItemEntity findById(Long id){
        Optional<EngItemEntity> optional  = repository.findById(id);
        if(optional.isPresent()) {
            EngItemEntity entity = optional.get();
            if(StringUtils.isNotBlank(entity.getStore())) {
                entity.setStorebin(entity.getStore()+","+entity.getBin());
            }
            return optional.get();
        }
        return null;
    }

    public Boolean deleteAllById(String idStrs){
        SysUserDetails user = SecurityUtils.getUser();
        // 逻辑删除
        List<Long> ids = Arrays.asList(idStrs.split(",")).stream()
                .map(idStr -> Long.parseLong(idStr)).collect(Collectors.toList());
        for(Long id:ids) {
            Optional<EngItemEntity> optional  = repository.findById(id);
            if(optional.isPresent()) {
                EngItemEntity entity = optional.get();
                entity.setDeleted(1);

                entity.setUpdateBy(user.getUserId());
                entity.setUpdateName(user.getUsername());
                repository.save(entity);
            }
        }
        return true;
    }
}


